package com.libraries.helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.libraries.image.activity.ImageClipviewActivity;
import com.libraries.image.activity.ImageSelectActivity;
import com.libraries.settings.SystemBarTintManager;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 获取设备信息辅助类
 * @author Wellsa
 *
 */
@SuppressLint("NewApi")
public class DeviceHelper {

	private static final String TAG = "DeviceHelper";

	// 上网类型
	/** 没有网络 */
	public static final byte NETWORK_TYPE_INVALID = 0x0;
	/** wifi网络 */
	public static final byte NETWORK_TYPE_WIFI = 0x1;
	/** 3G和3G以上网络，或统称为快速网络 */
	public static final byte NETWORK_TYPE_3G = 0x2;
	/** 2G网络 */
	public static final byte NETWORK_TYPE_2G = 0x3;
	
	public static final String IMG_UNSPECIFIED = "image/*";

	public static final int DO_CANCEL_RESULT = 5; // 取消
	public static final int DO_CAMERA_RESULT = 6;// 拍照
	public static final int DO_GALLERY_RESULT = 7; // 相册
	public static final int DO_CROP_RESULT = 8;// 裁剪结果
	
	public static final int DO_QRCODE_RESULT = 9;// 裁剪结果

	public static int CROP_WIDTH = 100;// 设置裁剪图片的宽
	public static int CROP_HEIGHT = 100;// 设置裁剪图片的高
	
	//拍照后的图片
	public static File pictureFile;

	public static void setStatusBarColor(Activity activity,int color){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(activity,true);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(activity);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintResource(color);
	}
	
	@TargetApi(19) 
	private static void setTranslucentStatus(Activity activity,boolean on) {
		Window win = activity.getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		View bodyView =win.getDecorView().findViewById(android.R.id.content);
//		Logger.log(TAG, "setTranslucentStatus", top,);
		if (bodyView!=null) {
			int top=getStatusHeight(activity);
			bodyView.setPadding(0, top, 0, 0);
		}
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}
	
	public static String getPhoneno(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getLine1Number();
	}

	/**
	 * 获取imsi号
	 * 
	 * @param context
	 */
	public static String getImsi(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imsi = tm.getSubscriberId();
		if (imsi != null && !imsi.equals("")) {
			if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
				// 因为移动网络编号46000下的IMSI已经用完，所以虚拟了一个46002编号，134/159号段使用了此编号
				//
				return "中国移动";
			} else if (imsi.startsWith("46001")) {
				// 中国联通
				return "中国联通";
			} else if (imsi.startsWith("46003")) {
				// 中国电信
				return "中国电信";
			}
		}
		return imsi;
	}

	/**
	 * 双卡双待手机获取imsi号， 能获取2个
	 * 
	 * @param context
	 * @param cardID
	 *            card1:0; card2:1
	 * @return
	 */
	public static String getDoubleImsi(Context context, int cardID) {
		String imsi = null;
		if (context == null) {
			return null;
		}
		if (cardID < 0 || cardID > 1) {
			return null;
		}
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		try {
			Class<?> mLoadClass = Class
					.forName("android.telephony.TelephonyManager");

			Class<?>[] parameter = new Class[1];
			parameter[0] = int.class;
			Method getSubscriberIdGemini = mLoadClass.getMethod(
					"getSubscriberIdGemini", parameter);

			Object[] obParameter = new Object[1];

			Object ob_imsi = null;

			obParameter[0] = cardID;
			ob_imsi = getSubscriberIdGemini.invoke(telephonyManager,
					obParameter);

			if (ob_imsi != null) {
				imsi = ob_imsi.toString();
			}

		} catch (Exception e) {
			e.printStackTrace();
			Logger.log(TAG, "getDoubleImsi err" + e.toString());
		}
		return imsi;
	}

	/**
	 * 获取imei号(需要 READ_PHONE_STATE权限)
	 * @return
	 */
	public static String getImei(Context context) {
		String imei = "000000000000000";
		try {
			TelephonyManager tm = (TelephonyManager)context
					.getSystemService(Context.TELEPHONY_SERVICE);
			imei = tm.getDeviceId();
		} catch (Exception e) {
			Logger.log(TAG, "getImei err" + e.toString());
		}
		return imei;
	}

	/**
	 * Returns the MCC+MNC (mobile country code + mobile network code) of the
	 * provider of the SIM. 5 or 6 decimal digits.
	 * 获取SIM卡提供的移动国家码和移动网络码.5或6位的十进制数字. SIM卡的状态必须是
	 * SIM_STATE_READY(使用getSimState()判断).
	 * 
	 * @param context
	 * @return
	 */
	public static String getSimOperator(Context context) {
		String operator = "";
		try {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			operator = tm.getSimOperator();// String
		} catch (Exception e) {
			Logger.log(TAG, "getSimOperator err" + e.toString());
		}
		return operator;
	}

	/**
	 * 服务商名称： 例如：中国移动、联通 SIM卡的状态必须是 SIM_STATE_READY(使用getSimState()判断).
	 * 
	 * @param context
	 * @return
	 */
	public static String getSimOperatorName(Context context) {
		String operatorName = "";
		try {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
				operatorName = tm.getSimOperatorName();// String
			}
		} catch (Exception e) {
			Logger.log(TAG, "getSimOperatorName err" + e.toString());
		}
		return operatorName;
	}

	/**
	 * 获取手机厂商名称
	 * @return
	 */
	public static String getProduct() {
		return android.os.Build.PRODUCT ;
	}
	
	/**
	 * 获取手机厂商名称
	 * @return
	 */
	public static String getModel () {
		return android.os.Build.MODEL ;
	}
	
	/**
	 * 获取手机厂商名称
	 * @return
	 */
	public static String getBrand() {
		return android.os.Build.BRAND ;
	}

	/**
	 * 获取程序版本号
	 * 
	 * @return
	 */
	public static int getVersionCode(Context context) {
		// 获取packagemanager的实例
		PackageManager packageManager =context
				.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return packInfo.versionCode ;
	}
	
	/**
	 * 获取程序版本名
	 * 
	 * @return
	 */
	public static String getVersionName(Context context) {
		// 获取packagemanager的实例
		PackageManager packageManager =context
				.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return packInfo.versionName ;
	}

	/**
	 * 获取系统版本号
	 * 
	 * @return
	 */
	public static int getSysVersionCode() {
		return Build.VERSION.SDK_INT;
	}

	/**
	 * 获取系统版本名
	 * 
	 * @return
	 */
	public static String getSysVersionName() {
		return Build.VERSION.RELEASE;
	}

	/**
	 * 获取MAC地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getMacAddr(Context context) {
		// 在wifi未开启状态下，仍然可以获取MAC地址，但是IP地址必须在已连接状态下否则为0
		String macAddress = null;
		WifiManager wifiMgr = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			macAddress = info.getMacAddress();
		}
		if (macAddress == null) {
			macAddress = "";
		}
		return macAddress;
	}

	public static String getCpuName() {
		FileReader fr = null;
		BufferedReader br = null;
		String[] array = null;
		try {
			fr = new FileReader("/proc/cpuinfo");
			br = new BufferedReader(fr);
			String text = br.readLine();
			array = text.split(":\\s+", 2);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (fr != null) {
					fr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (array != null && array.length >= 2) {
			return array[1];
		}
		return null;
	}
	
	/**
	 * Gets the number of cores available in this device, across all processors.
	 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
	 * @return The number of cores, or 1 if failed to get result
	 */
	public static int getCpuCount() {
	    //Private Class to display only CPU devices in the directory listing
	    class CpuFilter implements FileFilter {
	        @Override
	        public boolean accept(File pathname) {
	            //Check if filename is "cpu", followed by a single digit number
	            if(Pattern.matches("cpu[0-9]", pathname.getName())) {
	                return true;
	            }
	            return false;
	        }      
	    }

	    try {
	        //Get directory containing CPU info
	        File dir = new File("/sys/devices/system/cpu/");
	        //Filter to only list the devices we care about
	        File[] files = dir.listFiles(new CpuFilter());
	        //Return the number of cores (virtual CPU devices)
	        return files.length;
	    } catch(Exception e) {
	        //Default to return 1 core
	        return 1;
	    }
	}

	/**
	 * 获取网络状态，wifi,3g,2g,无网络。
	 * 
	 * @param context
	 *            上下文
	 * @return byte 网络状态 {@link #NETWORK_TYPE_WIFI}, {@link #NETWORK_TYPE_3G},
	 *         {@link #NETWORK_TYPE_2G}, {@link #NETWORK_TYPE_INVALID}
	 */
	public static byte getNetWorkType(Context context) {
		byte mNetWorkType = NETWORK_TYPE_INVALID;
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = manager.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.isConnected()) {
			int nType = networkInfo.getType();
			if (nType == ConnectivityManager.TYPE_WIFI) {
				mNetWorkType = NETWORK_TYPE_WIFI;
			} else if (nType == ConnectivityManager.TYPE_MOBILE) {
				// String proxyHost =
				// android.net.Proxy.getDefaultHost();//TextUtils.isEmpty(proxyHost)=false为wap网络
				mNetWorkType = (isFastMobileNetwork(context) ? NETWORK_TYPE_3G
						: NETWORK_TYPE_2G);
			}
		} else {
			mNetWorkType = NETWORK_TYPE_INVALID;
		}

		return mNetWorkType;
	}

	/**
	 * 判断是2G网络还是3G以上网络 false:2G网络;true:3G以上网络
	 */
	private static boolean isFastMobileNetwork(Context context) {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		switch (telephonyManager.getNetworkType()) {
		case TelephonyManager.NETWORK_TYPE_UNKNOWN:// 0
			return false;
		case TelephonyManager.NETWORK_TYPE_GPRS:// 1
			return false; // ~ 100 kbps
		case TelephonyManager.NETWORK_TYPE_EDGE:// 2
			return false; // ~ 50-100 kbps
		case TelephonyManager.NETWORK_TYPE_UMTS:// 3
			return true; // ~ 400-7000 kbps
		case TelephonyManager.NETWORK_TYPE_CDMA:// 4
			return false; // ~ 14-64 kbps
		case TelephonyManager.NETWORK_TYPE_EVDO_0:// 5
			return true; // ~ 400-1000 kbps
		case TelephonyManager.NETWORK_TYPE_EVDO_A:// 6
			return true; // ~ 600-1400 kbps
		case TelephonyManager.NETWORK_TYPE_1xRTT:// 7
			return false; // ~ 50-100 kbps
		case TelephonyManager.NETWORK_TYPE_HSDPA:// 8
			return true; // ~ 2-14 Mbps
		case TelephonyManager.NETWORK_TYPE_HSUPA:// 9
			return true; // ~ 1-23 Mbps
		case TelephonyManager.NETWORK_TYPE_HSPA:// 10
			return true; // ~ 700-1700 kbps
		case TelephonyManager.NETWORK_TYPE_IDEN:// 11
			return false; // ~25 kbps
			// SDK4.0才支持以下接口
		case 12:// TelephonyManager.NETWORK_TYPE_EVDO_B://12
			return true; // ~ 5 Mbps
		case 13:// TelephonyManager.NETWORK_TYPE_LTE://13
			return true; // ~ 10+ Mbps
		case 14:// TelephonyManager.NETWORK_TYPE_EHRPD://14
			return true; // ~ 1-2 Mbps
		case 15:// TelephonyManager.NETWORK_TYPE_HSPAP://15
			return true; // ~ 10-20 Mbps
		default:
			return false;
		}
	}

	public static Display getDisplay(Activity context) {
		return context.getWindowManager().getDefaultDisplay();
	}

	/**
	 * 是否触碰了Home键
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean onHome(Activity activity) {
		List<String> homes = getCurrentPkg(activity);
		ActivityManager mActivityManager = (ActivityManager) activity
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		return homes.contains(rti.get(0).topActivity.getPackageName());
	}

	private static List<String> getCurrentPkg(Activity activity) {
		List<String> packages = new ArrayList<String>();
		PackageManager packageManager = activity.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
				intent, PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo info : resolveInfo) {
			packages.add(info.activityInfo.packageName);
		}
		return packages;
	}

	/**
	 * 判断手机号是否正确
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean checkPhone(String phone) {
		if (phone.length() == 11) {
			Pattern pattern1 = Pattern.compile("^13\\d{9}||15[8,9]\\d{8}$");
			Pattern pattern2 = Pattern.compile("^15\\d{9}||15[8,9]\\d{8}$");
			Pattern pattern3 = Pattern.compile("^18\\d{9}||15[8,9]\\d{8}$");
			Pattern pattern4 = Pattern.compile("^17\\d{9}||15[8,9]\\d{8}$");
			Matcher matcher1 = pattern1.matcher(phone);
			Matcher matcher2 = pattern2.matcher(phone);
			Matcher matcher3 = pattern3.matcher(phone);
			Matcher matcher4 = pattern4.matcher(phone);
			if (matcher1.matches() || matcher2.matches() || matcher3.matches()|| matcher4.matches()) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断邮箱是否正确
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean checkEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 发送短信
	 * 
	 * @param smsBody
	 */
	public static void sendSms(Activity activity,String smsBody) {
		Uri smsToUri = Uri.parse("smsto:");
		Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
		intent.putExtra("sms_body", smsBody);
		activity.startActivity(intent);
	}

	/**
	 * 指定发送短信
	 * 
	 * @param smsBody
	 */

	public static void sendSms(Activity activity,String user, String smsBody) {
		Uri smsToUri;
		if (user == null || user.equals("")) {
			smsToUri = Uri.parse("smsto:");
		} else {
			smsToUri = Uri.parse("smsto:" + user);
		}
		Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
		intent.putExtra("sms_body", smsBody);
		activity.startActivity(intent);
	}

	/**
	 * 发送邮件
	 * 
	 * @param title
	 * @param content
	 */
	public static void sendEmail(Activity activity,String title, String content) {
		Uri uri = Uri.parse("mailto:");
		Intent data = new Intent(Intent.ACTION_SENDTO, uri);
		data.putExtra(Intent.EXTRA_SUBJECT, title);
		data.putExtra(Intent.EXTRA_TEXT, content);
		activity.startActivity(data);
	}

	/**
	 * 指定发送邮件
	 * 
	 * @param email
	 * @param title
	 * @param content
	 */
	public static void sendEmail(Activity activity,String email, String title, String content) {
		Intent data = new Intent(Intent.ACTION_SENDTO);
		if (email == null || email.equals("")) {
			sendEmail(activity,title, content);
			return;
		}
		data.setData(Uri.parse("mailto:" + email));
		data.putExtra(Intent.EXTRA_SUBJECT, title);
		data.putExtra(Intent.EXTRA_TEXT, content);
		activity.startActivity(data);
	}

	/**
	 * 复制
	 * 
	 * @param content
	 */
	@SuppressWarnings("deprecation")
	public static void doCopy(Context context,String content) {
		ClipboardManager cbm = (ClipboardManager) context
				.getSystemService(Context.CLIPBOARD_SERVICE);
		cbm.setText(content.trim());
	}

	/**
	 * 粘贴
	 *
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String doPaste(Context context) {
		// 得到剪贴板管理器
		ClipboardManager cmb = (ClipboardManager)context
				.getSystemService(Context.CLIPBOARD_SERVICE);
		return cmb.getText().toString().trim();
	}
	
	/**
	 * 打开网络设置界面
	 */
	public static void openSetting(Activity activity)
	{
		Intent intent = new Intent("/");
		ComponentName cm = new ComponentName("com.android.settings",
				"com.android.settings.WirelessSettings");
		intent.setComponent(cm);
		intent.setAction("android.intent.action.VIEW");
		activity.startActivityForResult(intent, 0);
	}
	
	/**
	 * 打开系统视频播放器
	 */
	public static void openVideo(Activity activity,String filePath)
	{
		  Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setDataAndType(Uri.parse("file://" + filePath), "video/*");
          activity.startActivity(intent);
	}
	

	/**
	 * 打开系统音乐播放器
	 */
	public static void openAudio(Activity activity,String filePath)
	{
		  Intent it = new Intent(Intent.ACTION_VIEW);
          it.setDataAndType(Uri.parse("file://" + filePath), "audio/*");
          activity.startActivity(it);          
	}
	
	/**
	 * 打开图库
	 * 
	 * @param activity
	 */
	public static void openGallery(Activity activity,boolean isMulti) {
		// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		// intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
		// IMG_UNSPECIFIED);
		Intent intent = new Intent(activity, ImageSelectActivity.class);
		intent.putExtra("isMulti", isMulti);
		activity.startActivityForResult(intent, DO_GALLERY_RESULT);
	}
	
	/**
	 * 打开图库
	 * 
	 * @param activity
	 */
	public static void openGallery(Activity activity,int requestCode) {
		// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		// intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
		// IMG_UNSPECIFIED);
		Intent intent = new Intent(activity, ImageSelectActivity.class);
		intent.putExtra("isMulti", true);
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 打开照相机
	 * 
	 * @param activity
	 */
	public static void openCamera(Activity activity) {
		String fileName = FileHelper.getFileName(".png");
		pictureFile = new File(FileHelper.getDiskCachePath(FileHelper.IMAGE_CACHE_DIR),fileName);
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureFile));
		activity.startActivityForResult(intent, DO_CAMERA_RESULT);
	}

	/**
	 * 裁剪图片
	 * 
	 * @param activity
	 * @param uri
	 */
	public static boolean doCropPhoto(Activity activity, String filePath,boolean clip) {
		Logger.log(TAG, "doCropPhoto", activity ,filePath,clip);
		Intent intent=null;
		if (clip) {
			intent = new Intent(activity,ImageClipviewActivity.class);
			intent.putExtra("filePath", filePath);
		}
		else{
			Uri fileUri=FileHelper.getUriByFile(filePath);
			if (fileUri == null) {
				return false;
			}
			intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(fileUri, "image/*");
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			// intent.putExtra("aspectX", 1);
			// intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", CROP_WIDTH);
			intent.putExtra("outputY", CROP_HEIGHT);
			intent.putExtra("return-data", true);
			intent.putExtra("noFaceDetection", true);
		}
		Logger.log(TAG, "doCropPhoto~",filePath,clip);
		activity.startActivityForResult(intent, DO_CROP_RESULT);
		return true;
	}
	
	/**
	 * 打卡软键盘
	 * 
	 * @param mEditText输入框
	 * @param mContext上下文
	 */
	public static void openKeybord(EditText mEditText, Context mContext)
	{
		InputMethodManager imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
				InputMethodManager.HIDE_IMPLICIT_ONLY);
	}

	/**
	 * 关闭软键盘
	 * 
	 * @param mEditText输入框
	 * @param mContext上下文
	 */
	public static void hideKeybord(EditText mEditText, Context mContext)
	{
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

		imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
	}

	/**
	 * 判断是否有卡在运行
	 */
	public static boolean isMountting() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}


	public static int computePageCount(int totalCount, int pageSize) {
		int pageCount = (int) Math.ceil(totalCount / (double) pageSize);
		return (pageCount == 0) ? 1 : pageCount;
	}

	/**
	 * 刷新媒体数据（应用拍照或摄像后调用）
	 * 
	 * @param context
	 */
	public static void doMediaScanner(Context context) {
		if (getSysVersionCode() < 19)
			context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
					.parse("file://"
							+ Environment.getExternalStorageDirectory())));
		else
			MediaScannerConnection.scanFile(context, new String[] { Environment
					.getExternalStorageDirectory().getPath() }, null, null);
	}

	/**
	 * whether context is system application
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isSysApplication(Context context) {
		if (context == null) {
			return false;
		}

		return isSysApplication(context, context.getPackageName());
	}

	/**
	 * whether packageName is system application
	 * 
	 * @param context
	 * @param pkgName
	 * @return
	 */
	public static boolean isSysApplication(Context context, String packageName) {
		if (context == null) {
			return false;
		}

		return isSystemApplication(context.getPackageManager(), packageName);
	}

	/**
	 * whether packageName is system application
	 * 
	 * @param packageManager
	 * @param packageName
	 * @return <ul>
	 *         <li>if packageManager is null, return false</li>
	 *         <li>if package name is null or is empty, return false</li>
	 *         <li>if package name not exit, return false</li>
	 *         <li>if package name exit, but not system app, return false</li>
	 *         <li>else return true</li>
	 *         </ul>
	 */
	public static boolean isSystemApplication(PackageManager packageManager,
			String packageName) {
		if (packageManager == null || packageName == null
				|| packageName.length() == 0) {
			return false;
		}

		try {
			ApplicationInfo app = packageManager.getApplicationInfo(
					packageName, 0);
			return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 获得状态栏的高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context)
	{

		int statusHeight = -1;
		try
		{
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 获取当前屏幕截图，包含状态栏
	 * 
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, 0, CURR_WIDTH, CURR_HEIGHT);
		view.destroyDrawingCache();
		return bp;

	}

	/**
	 * 获取当前屏幕截图，不包含状态栏
	 * 
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithoutStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		Rect frame = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, CURR_WIDTH, CURR_HEIGHT
				- statusBarHeight);
		view.destroyDrawingCache();
		return bp;

	}
	
	private static final float DEFAULT_WIDTH = 480;
	private static final float DEFAULT_HEIGHT = 800;
	public static int CURR_WIDTH;
	public static int CURR_HEIGHT;
	/**
	 * 根据传的宽度确定适合当前手机的图片宽
	 * 
	 * @param width
	 * @return
	 */
	public static int getFitWidth(int width) {
		return (int) ((CURR_WIDTH / DEFAULT_WIDTH) * width);
	}

	public static int getFitHeight(int height) {
		return (int) ((CURR_HEIGHT / DEFAULT_HEIGHT) * height);
	}
	
	/**
	 * dp转px
	 * 
	 * @param context
	 * @param val
	 * @return
	 */
	public static int dp2px(Context context, float dpVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dpVal, context.getResources().getDisplayMetrics());
	}

	/**
	 * sp转px
	 * 
	 * @param context
	 * @param val
	 * @return
	 */
	public static int sp2px(Context context, float spVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
				spVal, context.getResources().getDisplayMetrics());
	}

	/**
	 * px转dp
	 * 
	 * @param context
	 * @param pxVal
	 * @return
	 */
	public static float px2dp(Context context, float pxVal)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (pxVal / scale);
	}

	/**
	 * px转sp
	 * 
	 * @param fontScale
	 * @param pxVal
	 * @return
	 */
	public static float px2sp(Context context, float pxVal)
	{
		return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
	}
}
